package fm.controller;

import fm.entity.Activity;
import fm.entity.PublicNumber;
import fm.entity.ShareConfig;
import fm.entity.WxUser;
import fm.entityEnum.ActivityStatus;
import fm.entityEnum.ShareTypeEnum;
import fm.exception.BizException;
import fm.service.ActivityService;
import fm.service.PublicNumberService;
import fm.service.UserService;
import fm.util.CommonUtils;
import fm.util.Constant;
import fm.util.JsApiSignUtil;
import fm.util.WechatUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 类名：fm.controller.FlowMarketController
 * 创建者： CM .
 * 创建时间：2016/3/7
 */
@Controller
@RequestMapping("/activity/flow")
public class FlowMarketController extends BaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(FlowMarketController.class);
    @Autowired
    private ActivityService activityService;
    @Autowired
    UserService userService;
    @Autowired
    PublicNumberService publicNumberService;

    @Autowired
    UserService user;
    /**
     * @param request
     * @param modelMap
     * @param id          活动ID
     * @param uuid        公众号UUID
     * @param shareUserId 分享人ID
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String index(HttpServletRequest request, ModelMap modelMap,
                        @PathVariable(value = "id") Long id,
                        @RequestParam(value = "uuid") String uuid,
                        Long shareUserId) throws Exception {
        WxUser user = getCurrentUser();
        PublicNumber publicNumber = getCurrentPublicNumber();
        Activity activity = activityService.getById(id);

        if (!ActivityStatus.PROCESS.equals(activity.getStatus())) {
            throw new BizException("[" + activity.getId() + "]活动错误,状态：" + activity.getStatus().getDesc());
        }

        String accessToken = WechatUtils.getBaseAccessToken(publicNumber.getAppid(), publicNumber.getAppsecret(), Constant.GRANT_TYPE_CLIENT_CREDENTIAL, request);
        String ticket = WechatUtils.getJsApiTicket(request, accessToken, publicNumber.getUuid());
        Map sign = JsApiSignUtil.sign(ticket, request.getRequestURL().toString() + "?" + request.getQueryString());

        if (!CommonUtils.isEmpty(shareUserId)) {

            WxUser shareUser = userService.getById(shareUserId);
            ShareConfig shareConfig = activityService.getShareConfigBuyUser(shareUser);

            if (!CommonUtils.isEmpty(shareConfig)) {
                //用户配置过自定义分享的内容,注入对应的内容
                String shareActionUrl = shareConfig.getShareType().equals(ShareTypeEnum.LINK) ? shareConfig.getDownloadLink() : shareConfig.getTdCode();

                modelMap.put("targetUrl", shareActionUrl.trim());
                modelMap.put("shareType", shareConfig.getShareType().toString());

                LOGGER.debug("user(shareUserId={}) configuration share type:{}", shareUser.getId(), shareConfig.getShareType().toString());
            }
        }

        modelMap.put("sign", sign);
        modelMap.put("uuid", uuid);
        modelMap.put("appid", publicNumber.getAppid());
        modelMap.put("id", activity.getId());
        modelMap.put("title", activity.getTitle());
        modelMap.put("logo", activity.getLogoUrl());
        modelMap.put("desc", activity.getDescription());
        modelMap.put("url", activity.getLink() + "&shareId=" + user.getId());


        LOGGER.info("user(openid={}) request index page!", user.getOpenid());

        return "/market/index";
    }


    @RequestMapping(value = "/shake/{id}", method = RequestMethod.GET)
    public String shake(HttpServletRequest request, ModelMap modelMap,
                        @PathVariable(value = "id") Long id, @RequestParam(value = "tel") String tel,
                        @RequestParam(value = "uuid") String uuid) throws Exception {
        if (CommonUtils.isEmpty(uuid)) {
            throw new BizException("参数缺失，无法访问！");
        }
        WxUser user = getCurrentUser();
        PublicNumber publicNumber = publicNumberService.getByUuid(uuid);

        String accessToken = WechatUtils.getBaseAccessToken(publicNumber.getAppid(), publicNumber.getAppsecret(), Constant.GRANT_TYPE_CLIENT_CREDENTIAL, request);
        String ticket = WechatUtils.getJsApiTicket(request, accessToken, publicNumber.getUuid());
        Map sign = JsApiSignUtil.sign(ticket, request.getScheme() + "://" + request.getContextPath() + "/market/flow" + id + "?" + request.getQueryString());

        Activity activity = activityService.getById(id);
        if (!ActivityStatus.PROCESS.equals(activity.getStatus())) {
            throw new BizException("[" + activity.getId() + "]活动错误,状态：" + activity.getStatus().getDesc());
        }
        modelMap.put("appid", publicNumber.getAppid());
        modelMap.put("logo", activity.getLogoUrl());
        modelMap.put("title", activity.getTitle());
        modelMap.put("url", activity.getLink() + "&shareId=" + user.getId());
        modelMap.put("desc", activity.getDescription());

        modelMap.put("sign", sign);
        modelMap.put("tel", tel);
        LOGGER.info("user:{} -> shake", user.getNickname());
        return "/market/shake";
    }

    /**
     * 微信公众号分享API参数注入页面
     * 仅针对目前公众号所开发的活动 activity表
     *
     * @param request
     * @param modelMap
     * @param id       活动ID
     * @param uuid     公众号标识
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/share/config/{id}", method = RequestMethod.GET)
    public String shareConfig(HttpServletRequest request, ModelMap modelMap,
                              @PathVariable(value = "id") Long id, @RequestParam(value = "uuid") String uuid) throws Exception {
        if (CommonUtils.isEmpty(id) || CommonUtils.isEmpty(uuid)) {
            throw new BizException("参数缺失 无法访问");
        }
        WxUser user = getCurrentUser();
        ShareConfig shareConfig = activityService.getShareConfigBuyUser(user);
        if (!CommonUtils.isEmpty(shareConfig)) {
            modelMap.put("configed", Boolean.TRUE);
        } else {
            modelMap.put("configed", Boolean.FALSE);
        }
        PublicNumber publicNumber = publicNumberService.getByUuid(uuid);
        Activity activity = activityService.getById(id);
        String accessToken = WechatUtils.getBaseAccessToken(publicNumber.getAppid(), publicNumber.getAppsecret(), Constant.GRANT_TYPE_CLIENT_CREDENTIAL, request);
        String ticket = WechatUtils.getJsApiTicket(request, accessToken, publicNumber.getUuid());
        Map sign = JsApiSignUtil.sign(ticket, request.getRequestURL().toString() + "?" + request.getQueryString());

        modelMap.put("appid", publicNumber.getAppid());
        modelMap.put("logo", activity.getLogoUrl());
        modelMap.put("title", activity.getTitle());
        modelMap.put("url", activity.getLink() + "&shareId=" + user.getId());
        modelMap.put("sign", sign);
        modelMap.put("desc", activity.getDescription());
        modelMap.put("id", id);
        return "/market/share-config";
    }

}
